package lsf.itcast.controller;

import lsf.itcast.domain.Role;
import lsf.itcast.domain.UserInfo;
import lsf.itcast.service.RoleService;
import lsf.itcast.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
   private UserService userService;
    @Autowired
    private RoleService roleService;

    @RequestMapping("/findAll.do")
    public ModelAndView findAllUser(){
        ModelAndView mv = new ModelAndView();
        List<UserInfo> users = userService.findAll();
        mv.addObject("userList",users);
        mv.setViewName("user-list");
        return mv;
    }
    //查询用户详情，包含用户角色，用户的权限
    @RequestMapping("/findById.do")
    public ModelAndView findUserById(@RequestParam(required = true,name = "id") String id){
        ModelAndView mv = new ModelAndView();
        UserInfo userInfo= userService.findById(id);
        mv.addObject("user",userInfo);
        mv.setViewName("user-show1");
        return mv;
    }

    //新增用户
    @RequestMapping("/save.do")
    public String saveUser(UserInfo userInfo){
    userService.save(userInfo);
        return "redirect:findAll.do";
    }


    //给用户添加角色
    //1.根据userId，添加角色
    //2.给指定用户增加角色之后，返回到用户表
    @RequestMapping("/findUserByIdAndAllRole.do")
    public ModelAndView findUserByIdAndAllRole(@RequestParam(required = true,name = "id") String userId){
        ModelAndView mv = new ModelAndView();
        //根据id查询用户
        UserInfo userInfo = userService.findById(userId);
        //根据查询到的用户，在后台查询用户是否有角色
        List<Role> roles= roleService.findOtherRole(userId);
        mv.addObject("user",userInfo);
        mv.addObject("roleList",roles);
        mv.setViewName("user-role-add");
        return mv;
    }
    //根据users_role查询到userId,排除没有对应roleId的，然后给userId匹配角色，即roleId
    // 相当于给用户添加角色,即把角色ids添加到users_role中
     @RequestMapping("/addRoleToUser.do")
    public String addRoleToUser(@RequestParam(required =true, name="userId") String userId,@RequestParam(required =true, name="ids")String[] ids){
        userService.addRoleToUser(userId,ids);
        return "redirect:findAll.do";
     }
}
